<template>
  <div class="contrain">
    <div class="head">
      <span>邮箱登陆</span>
    </div>
    <div class="main">
      <van-form>
        <van-field v-model.trim="login.email"
                   label="邮箱"
                   name="pattern"
                   placeholder="请输入邮箱"
                   :rules="[{ validator:Emailvalidator, message:'请输入正确邮箱'}]" />
        <van-field v-model.trim="login.verify"
                   center
                   clearable
                   label="验证码">
          <template #button>
            <van-button size="small"
                        type="primary"
                        :disabled="isSend"
                        @click="sendEmail">
              <div v-if="!isSend">
                发送验证码
              </div>
              <div v-else
                   style="display: flex;align-items: center;">
                <van-count-down ref="countDown"
                                :time="60000"
                                :auto-start="false"
                                format="ss"
                                @finish="finish" />秒后可重新发送
              </div>
            </van-button>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round
                      block
                      type="info"
                      @click="EmailLogin"
                      native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import { getVerify } from '@/api/login'
export default {
  data () {
    return {
      isLoading: false,
      isSend: false,
      login: {
        email: '',
        verify: ''
      }
    }
  },
  methods: {
    sendEmail () {
      if (this.Emailvalidator(this.login.email) && this.login.email) {
        getVerify(this.login.email).then(res => {
          this.$toast.success(res.data)
          this.isSend = !this.isSend
          this.$nextTick(() => {
            this.$refs.countDown.start()
          })
        })
      } else {
        this.$toast.fail('请输入正确邮箱')
      }
    },
    finish () {
      this.isSend = !this.isSend
    },
    Emailvalidator (val) {
      return val ? /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(val) : true
    },
    EmailLogin () {
      this.$store.dispatch('emailLogin', this.login).then(() => {
        this.$toast.success('登陆成功')
        this.$router.push('/myself')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.contrain {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  padding: 30px;
  .head {
    margin-top: 20%;
    span {
      font-size: 24px;
    }
  }
  .main {
    margin-top: 15px;
    .van-field__label {
      margin-right: 0;
    }
  }
  .btn {
    margin-top: 15px;
    display: flex;
    width: 100%;
    flex-direction: column;
    p {
      margin-top: 15px;
      align-self: center;
    }
  }
}
</style>
